<template>
	<view class="uni-popup" :class="[popupClass]" v-show="showPopup" @touchmove.stop.prevent="clear">
		<view class="uni-popup__mask" :class="[maskClass]" @click="close(true)"></view>
		<view class="uni-popup__wrapper" :class="[wrapperClass]" @click="close(true)">
			<view class="uni-popup__wrapper-box" :class="[transClass]" @click.stop="clear">
				<slot />
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		name: 'UniPopup',
		props: {
			animation: {
				type: Boolean,
				default: true
			},
			type: {
				type: String,
				default: 'center'
			},
			maskClick: {
				type: Boolean,
				default: true
			},
			autoClose: {
				type: Boolean,
				default: true
			}
		},
		data() {
			return {
				popupWidth: 0,
				popupHeight: 0,
				deviceWidth: 0,
				deviceHeight: 0,
				showPopup: false,
				popupClass: '',
				maskClass: '',
				wrapperClass: '',
				transClass: ''
			}
		},
		created() {
			const systemInfo = uni.getSystemInfoSync()
			this.deviceWidth = systemInfo.windowWidth
			this.deviceHeight = systemInfo.windowHeight
		},
		methods: {
			clear(e) {
				e.stopPropagation()
			},
			open() {
				this.showPopup = true
				this.$emit('change', {
					show: true,
					type: this.type
				})
			},
			close(type) {
				if (!this.maskClick && type) return
				this.showPopup = false
				this.$emit('change', {
					show: false,
					type: this.type
				})
			}
		},
		watch: {
			type: {
				handler: function(newVal) {
					switch (newVal) {
						case 'top':
							this.popupClass = 'uni-top'
							this.maskClass = 'uni-top-mask'
							this.wrapperClass = 'uni-top-wrapper'
							this.transClass = 'uni-top-trans'
							break
						case 'bottom':
							this.popupClass = 'uni-bottom'
							this.maskClass = 'uni-bottom-mask'
							this.wrapperClass = 'uni-bottom-wrapper'
							this.transClass = 'uni-bottom-trans'
							break
						case 'center':
							this.popupClass = 'uni-center'
							this.maskClass = 'uni-center-mask'
							this.wrapperClass = 'uni-center-wrapper'
							this.transClass = 'uni-center-trans'
							break
					}
				},
				immediate: true
			}
		}
	}
</script>

<style lang="scss">
.uni-popup {
	position: fixed;
	top: 0;
	bottom: 0;
	left: 0;
	right: 0;
	z-index: 99999;
	overflow: hidden;

	&.uni-center {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.uni-popup__mask {
		position: absolute;
		top: 0;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: rgba(0, 0, 0, 0.4);
		opacity: 0;
		transition: opacity 0.3s;
	}

	.uni-popup__wrapper {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		z-index: 99999;

		.uni-popup__wrapper-box {
			position: relative;
			box-sizing: border-box;
			background-color: #fff;
			border-radius: 10rpx;
			overflow: hidden;
		}
	}
}

.uni-center-mask {
	opacity: 1 !important;
}

.uni-center-trans {
	opacity: 1;
	transition: opacity 0.3s;
}
</style> 